//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js')
const AV = require('../../libs/leancloud/av-weapp-min.js')

Page({
    data: {
        debug: false,
        // 广告位控制
        adShow: false,
        ad0Show: false,
        ad0ID: "",
        ad1Show: false,
        ad1ID: "",

        defaultBG: '../../images/test.jpg',
        canIUse: false,
        hasUserInfo: false,

        canvasWidth: 1,
        canvasHeight: 1,
        systemInfo: {},

        searchBGColor: '',

        // https://ae01.alicdn.com/kf/H159be3b332024195917804fee84df459I.png
        // https://ae01.alicdn.com/kf/H7affe1c339694af38c14ee676c5f2028u.png
        // https://ae01.alicdn.com/kf/Hc0761cdca8484cb892a674aa11a66a9e2.jpg
        // https://ae01.alicdn.com/kf/Hd79dd3a4f33d4ee685be8b9397825793R.jpg
        // https://ae01.alicdn.com/kf/H9e5d88dcf1944a0eb8258e0c0eb8d20e7.jpg
        swiperCtrlData: {
            "enable": true,
            "indicator_dots": false,
            "autoplay": false,
            "interval": 4000,
            "data": [
                {
                    id: 1,
                    url: 'https://ae01.alicdn.com/kf/H9e5d88dcf1944a0eb8258e0c0eb8d20e7.jpg',
                    title: '',
                    key: '',
                    password: ''
                }
            ]
        },
        swiperImgUrls: [
        ],
        menuFocusName: 'menu-all',
        menuFocusIndex: 0,
        scrollHeight: 0,
        navBarHeight: 0,
        contentHeight: 0,
        logoHeight: 0,
        fixMenuClass: '',
        scrollViewY: [
            false, false, false, false, false
        ],
        scrollViewPagePos: [
            0, 0, 0, 0,0
        ],
        displayBack2Top: [
            true, false, false, false, false
        ],
        displayFooter: 'block',
        isLoading: [
            false, false, false, false, false
        ],
        isLastPage: [
            false, false, false, false, false
        ],
        isFirsttimeLoad: [
            false, true, true, true, true
        ],
        currentPageIndex: [
            0, 0, 0, 0, 0
        ],
        colorArr: [
            "#7BA745", "#D0692E", "#A6D800", "#A0D7FF", "#8077E5", "#EC9CA6",
            "#FF8C00", "#89EE37", "#14D7FF", "#FFF53D", "#006989", "#A3BAC3",
            "#FFCB63", "#66BD84", "#ED6A5A", "#FF5D00", "#8FC93A", "#E4CC37",
            "#A8F9FF", "#43A3E8", "#F38A32", "#43AE24", "#EACD4F", "#EAD5E6",
            "#E18335", "#0B8193", "#FFFF00", "#5FFF0A", "#6DBDEB", "#1B98E0",
        ],
        blogDataPageNum: 0,
        blogDataList: [
        ],
        blogCategoryDataList: [
        ],
        blogTagDataList: [
        ],
        blogRankingList: [
            {
                id: "0",
                title: "排行榜出问题了...",
                page_views: 2000,
                comment_count: 100,
                thumbs_up_count: 111,
                url: "",
                date: "2019-10-05 10:49:00"
            }
        ],
        opensourceDataPageNum: 0,
        opensourceDataList: [
        ]
    },
    onLoad: function() {
        let that = this;
        this.calcViewsHeight();

        // 默认背景图片检查 & 广告位设置检查
        that.checkoutAD();

        // 动态获取图片顶部像素rgb值(真机无效bug，已反馈官方，证实是bug)
        //this.getPixelOfImage(that.data.swiperImgUrls[0].url);
        // 首次加载博文
        that.firstTimeLoadBlogPageData(function(status) {
            // 
        });

    },
    onShow: function () {
        let that = this;
        console.log('onShow');
        // 是否加载默认swiper数据或者网络控制数据
        if (app.globalData.config) {
            if (app.globalData.config.swiper.enable) {
                that.data.swiperCtrlData = app.globalData.config.swiper;
            } 
            that.setData({
                swiperCtrlData: that.data.swiperCtrlData
            })
        }
    },
    onShareAppMessage: function () {
        let that = this;
        return {
            title: 'xsb博客',
            path: '/pages/index/index'           
        }
    },
    checkoutAD: function () {
        let that = this;
        if (app.globalData.config) {
            that.data.defaultBG = app.globalData.config.global.default_bg;
            that.data.adShow = app.globalData.config.ad.show;
            that.data.ad0Show = app.globalData.config.ad.ad0.show;
            that.data.ad0ID = app.globalData.config.ad.ad0.id;
            that.data.ad1Show = app.globalData.config.ad.ad1.show;
            that.data.ad1ID = app.globalData.config.ad.ad1.id;
            that.setData({
                defaultBG: that.data.defaultBG,
                adShow: that.data.adShow,
                ad0Show: that.data.ad0Show,
                ad0ID: that.data.ad0ID,
                ad1Show: that.data.ad1Show,
                ad1ID: that.data.ad1ID
            })
        }
    },
    firstTimeLoadBlogPageData: function(call_back) {
        let that = this;
        that.data.currentPageIndex[0] = 0;
        that.data.isLastPage[0] = false;
        that.data.blogDataList = [];

        if (!that.data.isLastPage[0]) {
            wx.showLoading({
                title: '加载中...',
            })
            setTimeout(function () {
                wx.hideLoading()
            }, 8000)
            that.tryToFetchBlogDataPageNum(function (status, result) {
                if (status) {
                    that.fetchBlogDataList(that.data.currentPageIndex[0], function (status) {
                        // status为true，则获取数据成功
                        wx.hideLoading();
                        call_back(true)
                    });
                } else {
                    // 获取博文总页数失败
                    wx.hideLoading();
                    wx.showToast({
                        title: '获取博文出了点问题',
                        icon: 'none',
                        duration: 2000
                    });
                    that.data.isLastPage[0] = true;
                    that.setData({
                        isLastPage: that.data.isLastPage
                    })
                    call_back(false)
                }
            })
        }
    },
    calcViewsHeight: function() {
        let that = this
        let systemInfo = wx.getSystemInfoSync();
        that.data.systemInfo = systemInfo;
        let query = wx.createSelectorQuery().in(this);
        query.select('.container').boundingClientRect();
        query.select('.search').boundingClientRect();
        query.select('.content-display').boundingClientRect();
        query.select('.menu').boundingClientRect();
        query.select('.content').boundingClientRect();
        query.select('.header-logo').boundingClientRect();
        query.exec(res => {
            let container_h = res[0].height;
            let search_h = res[1].height;
            let content_display_h = res[2].height;
            let menu_h = res[3].height;
            let content_h = res[4].height;
            let header_logo_h = res[5].height;
            // console.log('container h: ' + container_h);
            // console.log('search h:' + search_h);
            // console.log('content display h:' + content_display_h);
            // console.log('menu h:' + menu_h);
            // console.log('content h:' + content_h);
            // console.log('header logo height: ' + header_logo_h);
            // console.log(systemInfo);
            let scroll_h = content_display_h - menu_h;
            that.setData({
                // scrollHeight: scroll_h,
                navBarHeight: search_h,
                contentHeight: systemInfo.windowHeight - search_h,
                // logoHeight: container_h - search_h
                //logoHeight: header_logo_h // if search box not fixed
            })

            let query_again = wx.createSelectorQuery().in(this);
            query_again.select('.menu').boundingClientRect();
            query_again.exec(res => {
                let new_menu_h = res[0].height;
                // console.log(new_menu_h);
            });
        });
    },
    onPageScroll(e) {
        let that = this;
        if (that.data.debug) {
            console.log("page scroll pos: " + e.scrollTop);
        }
        let key0 = 'scrollViewY[0]';
        let key1 = 'scrollViewY[1]';
        let key2 = 'scrollViewY[2]';
        let key3 = 'scrollViewY[3]';
        let key4 = 'scrollViewY[4]';
        if (e.scrollTop > that.data.logoHeight && !that.data.fixMenuClass) {
            if (that.data.debug) {
                console.log('scroll view ' + that.data.menuFocusIndex + ' enable');
            }
            that.setData({
                fixMenuClass: 'menu-fixed',
                [key0]: true,
                [key1]: true,
                [key2]: true,
                [key3]: true,
                [key4]: true
            })
        } else if (e.scrollTop <= 0) {
            console.log('scroll view disable');
            that.setData({
                fixMenuClass: '',
                [key0]: false,
                [key1]: false,
                [key2]: false,
                [key3]: false,
                [key4]: false
            })
        }
    },
    getUserInfo: function(e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    swiperChange: function(e) {
        let that = this;
        //console.log(e.detail.current);
        //console.log(that.data.swiperImgUrls[e.detail.current].url)
        //this.getPixelOfImage(that.data.swiperImgUrls[e.detail.current].url);
    },
    onReachBottom: function() {
        console.log('onReachBottom');
    },
    tapMenuAll: function(e) {
        console.log("menu-all e:",e);
        console.log(e.currentTarget.dataset.name);
        let that = this;
        let name = e.currentTarget.dataset.name;
        let key0 = 'scrollViewPagePos[0]';
        that.setData({
            menuFocusName: name,
            // menuFocusIndex: 0,
            [key0]: that.data.scrollViewPagePos[0]
        })
    },
    tapMenuCategory: function(e) {
        //console.log(e);
        console.log(e.currentTarget.dataset.name);
        let that = this;
        let name = e.currentTarget.dataset.name;
        let key1 = 'scrollViewPagePos[1]';
        that.setData({
            menuFocusName: name,
            // menuFocusIndex: 1,
            [key1]: that.data.scrollViewPagePos[1]
        })

        // 获取网络数据
        if (that.data.isFirsttimeLoad[1] && !that.data.isLoading[1]) {
            let loading1 = 'isLoading[1]';
            that.setData({
                [loading1]: true
            })
            that.fetchCategoriesInfo(function(status, result){
                let loading1 = 'isLoading[1]';
                that.setData({
                    [loading1]: false
                })
                //console.log(result)
                if (status) {
                    that.setData({
                        blogCategoryDataList: result
                    })
                    that.data.isFirsttimeLoad[1] = false;
                } else {
                    // 加载种类信息数据失败   
                }
                // 一次加载，不分页
                that.data.isLastPage[1] = true;
                that.setData({
                    isLastPage: that.data.isLastPage
                }) 
            });
        }
    },
    tapMenuTag: function(e) {
        //console.log(e);
        console.log(e.currentTarget.dataset.name);
        let that = this;
        let name = e.currentTarget.dataset.name;
        let key2 = 'scrollViewPagePos[2]';
        that.setData({
            menuFocusName: name,
            // menuFocusIndex: 2,
            [key2]: that.data.scrollViewPagePos[2]
        })
        // 获取网络数据
        if (that.data.isFirsttimeLoad[2] && !that.data.isLoading[2]) {
            let loading2 = 'isLoading[2]';
            that.setData({
                [loading2]: true
            })
            that.fetchTagsInfo(function (status, result) {
                let loading2 = 'isLoading[2]';
                that.setData({
                    [loading2]: false
                })
                if (status) {
                    that.setData({
                        blogTagDataList: result
                    })
                    that.data.isFirsttimeLoad[2] = false;
                } else {
                    // 加载标签信息数据失败   
                }
                // 一次加载，不分页
                that.data.isLastPage[2] = true;
                that.setData({
                    isLastPage: that.data.isLastPage
                })
            });
        }
    },
    tapMenuOpenSource: function(e) {
        //console.log(e);
        console.log(e.currentTarget.dataset.name);
        let that = this;
        let name = e.currentTarget.dataset.name;
        let key3 = 'scrollViewPagePos[3]';
        that.setData({
            menuFocusName: name,
            // menuFocusIndex: 3,
            [key3]: that.data.scrollViewPagePos[3]
        })
        // 获取网络数据
        if (that.data.isFirsttimeLoad[3] && !that.data.isLoading[3]) {
            let loading3 = 'isLoading[3]';
            that.setData({
                [loading3]: true
            })
            that.tryToFetchOpensourceDataPageNum(function (status, result) {
                if (status) {
                    that.fetchOpensourceDataList(that.data.currentPageIndex[3], function (status) {
                        // status为true，则获取数据成功
                        if (status) {
                            that.data.isFirsttimeLoad[3] = false;
                        }
                        
                        that.setData({                        
                            [loading3]: false
                        })
                    });
                } else {
                    // 获取博文总页数失败
                    wx.showToast({
                        title: '获取开源项目信息出了点问题',
                        icon: 'none',
                        duration: 2000
                    });
                    that.data.isLastPage[3] = true;
                    that.setData({
                        isLastPage: that.data.isLastPage,
                        [loading3]: false
                    })
                }
            })
        }
    },
    tapMenuRankingList: function(e) {
        //console.log(e);
        console.log(e.currentTarget.dataset.name);
        let that = this;
        let name = e.currentTarget.dataset.name;
        let key4 = 'scrollViewPagePos[4]';
        that.setData({
            menuFocusName: name,
            menuFocusIndex: 4,
            [key4]: that.data.scrollViewPagePos[4]
        })
        // 获取数据
        if (that.data.isFirsttimeLoad[4]) {
            that.data.blogRankingList = []
            that.fetchTopNArticle('time', 15, function(status, results){
                if (status) {
                    //console.log(results);
                    for (let i = 0; i < results.length; i++) {
                        // id: "0",
                        // title: "测试标题1",
                        // page_views: 200,
                        // comment_count: 10,
                        // thumbs_up_count: 11,
                        // date: "2019-10-05 10:49:00"                        
                        let item = {
                            id: results[i].id,
                            title: results[i].attributes.title,
                            page_views: results[i].attributes.time,
                            comment_count: results[i].attributes.comments,
                            thumbs_up_count: results[i].attributes.likeUserList == undefined ? 0 : results[i].attributes.likeUserList.length,
                            url: results[i].attributes.url,
                            date: util.getLocalDateTimeStr(results[i].createdAt)
                        }
                        that.data.blogRankingList.push(item)                    
                    }
                    that.data.isFirsttimeLoad[4] = false;
                    that.setData({
                        blogRankingList: that.data.blogRankingList
                    })
                } else {

                }
            })
        }
    },
    tapRankingItem: function(e) {
        console.log(e);
        let title = e.currentTarget.dataset.title;
        let url = e.currentTarget.dataset.url;
        let url_split = url.split('/');
        let key = url_split[2].split('.')[0];
        let password = e.currentTarget.dataset.password ? e.currentTarget.dataset.password : ''; 
        let password_desc = e.currentTarget.dataset.password_desc ? e.currentTarget.dataset.password : ''; 

        wx.navigateTo({
            url: '../detail/detail?title=' + title + '&key=' + key + '&password=' + password
                + '&password_desc=' + password_desc,
            success: function () {
                // nothing to do
            },
            fail: function () {
                console.error("打开链接失败");
            }
        })
    },
    backToTop: function(e) {
        let that = this;
        let id = e.currentTarget.dataset.id;
        if (id == '0') {
            let key0 = 'scrollViewPagePos[0]';
            that.setData({
                // 值1, 否则scroll view 会 disable
                [key0] : 1
            })
        }
    },
    scrollToLower: function(e) {
        // console.log(e);
        let that = this;
        let id = e.currentTarget.dataset.id;
        if (!that.data.isLastPage[0] && id == '0' && !that.data.isLoading[0]) {
            let loading0 = 'isLoading[0]';
            that.setData({
                [loading0]: true
            })
            that.tryToFetchBlogDataPageNum(function (status, result) {
                if (status) {
                    that.fetchBlogDataList(that.data.currentPageIndex[0], function(status) {
                        that.setData({
                            [loading0]: false
                        })
                    });
                } else {
                    // 获取博文总页数失败
                    that.setData({
                        [loading0]: false
                    })
                }
            })
        } else if (!that.data.isLastPage[3] && id == '3' && !that.data.isLoading[3]) {
            // 开源项目
            let loading3 = 'isLoading[3]';
            that.setData({
                [loading3]: true
            })
            that.tryToFetchOpensourceDataPageNum(function (status, result) {
                if (status) {
                    that.fetchOpensourceDataList(that.data.currentPageIndex[3], function (status) {
                        that.setData({
                            [loading3]: false
                        })
                    });
                } else {
                    // 获取开源项目总页数失败
                    that.setData({
                        [loading3]: false
                    })
                }
            })
        }
    },
    scrollViewPos: function(e) {
        let that = this;
        if (that.data.debug) {
            console.log('scroll view pos: ' + e.detail.scrollTop);
        }
        that.data.scrollViewPagePos[that.data.menuFocusIndex] = e.detail.scrollTop;
        if (e.detail.scrollTop <= 0) {
            let key0 = 'scrollViewY[0]';
            let key1 = 'scrollViewY[1]';
            let key2 = 'scrollViewY[2]';
            let key3 = 'scrollViewY[3]';
            let key4 = 'scrollViewY[4]';
            if (that.data.debug) {
                console.log('scroll view ' + that.data.menuFocusIndex + ' disable by scroll pos');
            }
            that.setData({
                fixMenuClass: '',
                [key0]: false,
                [key1]: false,
                [key2]: false,
                [key3]: false,
                [key4]: false
            });
            // 出现头部图片则将所有scroll-view位置值清零
            that.data.scrollViewPagePos[0] = 0;
            that.data.scrollViewPagePos[1] = 0;
            that.data.scrollViewPagePos[2] = 0;
            that.data.scrollViewPagePos[3] = 0;
            that.data.scrollViewPagePos[4] = 0;
        }
    },
    getPixelOfImage: function(img_path) {
        let that = this;
        let ctx = wx.createCanvasContext('canone', that);
        if (!ctx) {
            console.log('failed to create canvas content');
            return;
        }
        // 获取图片信息
        wx.getImageInfo({
            src: img_path,
            success(res) {
                console.log(res.width)
                console.log(res.height)
                let img_w = res.width;
                let img_h = res.height;
                // 只选区左上角一个像素
                ctx.drawImage(img_path, 0, 0, img_w, img_h);

                ctx.draw(false, setTimeout(function(e) {
                    console.log('draw');
                    wx.canvasGetImageData({
                        canvasId: 'canone',
                        x: 0,
                        y: 0,
                        width: img_w,
                        height: img_h,
                        success: function(res) {
                            console.log('success');
                            let pixels = res.data;
                            //let pixelCount = width * height;
                            //for (let i = 0, offset, r, g, b, a; i < 1; i = i + quality) {
                            let i = 0;
                            let offset = 0;
                            offset = i * 4;
                            let r = pixels[offset + 0];
                            let g = pixels[offset + 1];
                            let b = pixels[offset + 2];
                            let a = pixels[offset + 3];
                            console.log(res.width)
                            console.log(res.height)
                            console.log(res.data instanceof Uint8ClampedArray)
                            console.log(res.data.length)

                            console.log(r + ',' + g + ',' + b);
                            let search_bg_color = 'rgb(' + r + ',' + g + ',' + b + ')';
                            console.log(search_bg_color);
                            that.setData({
                                searchBGColor: search_bg_color
                            });

                            wx.setBackgroundColor({
                                backgroundColor: search_bg_color
                            })
                        },
                        fail: function(res) {
                            console.log('fail')
                        }
                    }, that)
                }, 500))
            }
        })
    },
    chooseArticle: function(e) {        
        let key = e.currentTarget.dataset.key;
        let author = e.currentTarget.dataset.author;
        let comment_count = e.currentTarget.dataset.comment_count;
        let page_views = e.currentTarget.dataset.page_views;
        let thumbs_up_count = e.currentTarget.dataset.thumbs_up_count;
        let title = e.currentTarget.dataset.title;
        let date = e.currentTarget.dataset.date;
        let cover = e.currentTarget.dataset.cover;
        let desc = e.currentTarget.dataset.desc;
        let password = e.currentTarget.dataset.password ? e.currentTarget.dataset.password : '';
        let password_desc = e.currentTarget.dataset.password_desc ? e.currentTarget.dataset.password : ''; ;

        wx.navigateTo({
            url: '../detail/detail?title=' + title + '&key=' + key + '&author=' + author 
                + '&comment_count=' + comment_count + '&page_views=' + page_views 
                + '&thumbs_up_count=' + thumbs_up_count + '&date=' + date + '&password=' + password
                + '&password_desc=' + password_desc
                + '&cover=' + cover + '&desc=' + desc,
            success: function () {
                // nothing to do
            },
            fail: function () {
                console.error("打开链接失败");
            }
        })
    },
    /*
     * 所有 
     */
    tryToFetchBlogDataPageNum: function(call_back) {
        let that = this;
        if (that.data.blogDataPageNum > 0) {
            // 已经获取
            call_back(true, that.data.blogDataPageNum);
            return ;
        }

        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_top_pages/page.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求博文页数数据成功');
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);
                that.data.blogDataPageNum = parse_res.total_pages;
                call_back(true, that.data.blogDataPageNum);
            },
            fail: function (e) {
                console.log('请求博文页数数据失败');
                call_back(false, null);
            }
        })
    },
    fetchBlogDataList: function(page_num, call_back) {
        let that = this;
        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_top_pages/' + page_num + '.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求博文页列表数据成功,res:',res);
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);
                // 当前页偏移+1
                that.data.currentPageIndex[0] = that.data.currentPageIndex[0] + 1;
                if (that.data.currentPageIndex[0] >= that.data.blogDataPageNum) {
                    that.data.isLastPage[0] = true;
                }

                console.log("parse_res:",parse_res);
                let keys = [];
                for (let i = 0; i < parse_res.length; i++) {
                    let key = '/' + parse_res[i].key.substr(0, 4) + '/' + parse_res[i].key + '.html';
                    keys.push(key);
                }

                that.fetchArticleStatisticsData(keys, function(status, result){
                    if (status) {
                        for (let i = 0; i < parse_res.length; i++) {
                            let j = 0;
                            for (j; j < result.length; j++) {
                                let key = '/' + parse_res[i].key.substr(0, 4) + '/' + parse_res[i].key + '.html';
                                if (key == result[j].attributes.url) {
                                    parse_res[i]["page_views"] = result[j].attributes.time == undefined ? 0 : result[j].attributes.time;
                                    parse_res[i]["comment_count"] = result[j].attributes.comments == undefined ? 0 : result[j].attributes.comments;
                                    parse_res[i]["thumbs_up_count"] = result[j].attributes.likeUserList == undefined ? 0 : result[j].attributes.likeUserList.length;
                                    break;
                                }
                            }
                            if (j == result.length) {
                                // 还未创建文章统计数据
                                parse_res[i]["page_views"] = 0;
                                parse_res[i]["comment_count"] = 0;
                                parse_res[i]["thumbs_up_count"] = 0;            
                            }
                        } 
                        that.data.blogDataList = [].concat(that.data.blogDataList, parse_res);
                        that.setData({
                            blogDataList: that.data.blogDataList,
                            isLastPage: that.data.isLastPage
                        })
                        // 回调返回结果
                        call_back(true)
                    } else {
                        // 获取每页文章统计数据失败
                        call_back(false)
                    }
                });
            },
            fail: function (e) {
                console.log('请求博文页列表数据失败');
                call_back(false);
            }
        })
    },
    fetchArticleStatisticsData: function(keys, call_back) {
        let query = new AV.Query('Counter');
        query.containedIn('url', keys);
        query.find().then(ret => {
            //console.log(ret)
            call_back(true, ret);
        }).catch(ex => {
            console.log(ex.message);
            console.log(ex.code);
            if (ex.code == 101) {
                console.log('页面统计表未存在');
            }
            call_back(false, null);
        });
    },
    /*
     * 种类 
     */
    fetchCategoriesInfo: function (call_back) {
        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_categories_pages/categories_info_output.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求博文种类信息数据成功');
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);           
                call_back(true, parse_res);
            },
            fail: function (e) {
                console.log('请求博文种类信息数据失败');
                call_back(false, null);
                wx.showToast({
                    title: '获取博文种类数据出了点问题',
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
    /*
     * 标签
     */
    fetchTagsInfo: function (call_back) {
        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_tags_pages/tags.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求博文标签信息数据成功');
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);
                call_back(true, parse_res);
            },
            fail: function (e) {
                console.log('请求博文标签信息数据失败');
                call_back(false, null);
                wx.showToast({
                    title: '获取博文标签数据出了点问题',
                    icon: 'none',
                    duration: 2000
                })
            }
        })
    },
    /*
     * 开源项目
     */
    tryToFetchOpensourceDataPageNum: function (call_back) {
        let that = this;
        if (that.data.opensourceDataPageNum > 0) {
            // 已经获取
            call_back(true, that.data.opensourceDataPageNum);
            return;
        }

        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_top_opensource_pages/开源/page.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求开源项目页数数据成功');
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);                
                that.data.opensourceDataPageNum = parse_res.total_pages;
                call_back(true, that.data.opensourceDataPageNum);
            },
            fail: function (e) {
                console.log('请求开源项目页数数据失败');
                call_back(false, null);
            }
        })
    },
    fetchOpensourceDataList: function (page_num, call_back) {
        let that = this;
        wx.request({
            url: app.globalData.gitee.target_url + '/blog_time_top_opensource_pages/开源/' + page_num + '.json',
            data: {
                access_token: app.globalData.gitee.access_token,
                ref: app.globalData.gitee.branch
            },
            success: function (res) {
                console.log('请求开源项目页列表数据成功');
                let output = app.base64.decode(res.data.content);
                let parse_res = JSON.parse(output);
                // 当前页偏移+1                
                that.data.currentPageIndex[3] = that.data.currentPageIndex[3] + 1;                
                if (that.data.currentPageIndex[3] >= that.data.opensourceDataPageNum) {
                    that.data.isLastPage[3] = true;
                }

                //console.log(parse_res);
                let keys = [];
                for (let i = 0; i < parse_res.length; i++) {
                    let key = '/' + parse_res[i].key.substr(0, 4) + '/' + parse_res[i].key + '.html';
                    keys.push(key);
                }

                that.fetchArticleStatisticsData(keys, function (status, result) {
                    if (status) {
                        for (let i = 0; i < parse_res.length; i++) {
                            let j = 0;
                            for (j; j < result.length; j++) {
                                let key = '/' + parse_res[i].key.substr(0, 4) + '/' + parse_res[i].key + '.html';
                                if (key == result[j].attributes.url) {
                                    parse_res[i]["page_views"] = result[j].attributes.time == undefined ? 0 : result[j].attributes.time;
                                    parse_res[i]["comment_count"] = result[j].attributes.comments == undefined ? 0 : result[j].attributes.comments;
                                    parse_res[i]["thumbs_up_count"] = result[j].attributes.likeUserList == undefined ? 0 : result[j].attributes.likeUserList.length;
                                    break;
                                }
                            }
                            if (j == result.length) {
                                // 还未创建文章统计数据
                                parse_res[i]["page_views"] = 0;
                                parse_res[i]["comment_count"] = 0;
                                parse_res[i]["thumbs_up_count"] = 0;
                            }
                        }
                        that.data.opensourceDataList = [].concat(that.data.opensourceDataList, parse_res);
                        that.setData({
                            opensourceDataList: that.data.opensourceDataList,
                            isLastPage: that.data.isLastPage
                        })
                        // 回调返回结果
                        call_back(true)
                    } else {
                        // 获取每页文章统计数据失败
                        call_back(false)
                    }
                });
            },
            fail: function (e) {
                console.log('请求博文页列表数据失败');
                call_back(false);
            }
        })
    },
    fetchTopNArticle: function(property, limit, call_back) {
        var query = new AV.Query('Counter');
        query.descending(property);
        query.contains('url', '.html');
        query.contains('tag', 'blog');
        query.limit(limit);        
        query.find().then(ret => {
            //console.log(ret)
            call_back(true, ret);
        }).catch(ex => {
            console.log(ex.message);
            console.log(ex.code);
            if (ex.code == 101) {
                console.log('页面统计表未存在');
            }
            wx.showToast({
                title: '加载博文排行榜失败',
                icon: 'none',
                duration: 2000
            })
            call_back(false, null);        
        });
    },
    search: function (e) {
        wx.showToast({
            title: 'Coming soon',
            icon: 'none',
            duration: 2000
        })
    },
    adLoadError: function(e) {
        console.log(e.detail)
        let that = this;
        let index = e.currentTarget.dataset.index;        
        that.data.blogDataList[index].cover_show = true
        that.setData({
            blogDataList: that.data.blogDataList
        })
    },
    adLoadSuccess: function(e) {
        console.log('Banner广告加载成功')
        let that = this;
        let index = e.currentTarget.dataset.index;
        that.data.blogDataList[index].cover_show = false
        that.setData({
            blogDataList: that.data.blogDataList
        })
    },
    swiperItemTap: function(e) {
        let title = e.currentTarget.dataset.title;
        let cover = e.currentTarget.dataset.cover;
        let key = e.currentTarget.dataset.key;        
        let password = e.currentTarget.dataset.password ? e.currentTarget.dataset.password : '';        
        let password_desc = e.currentTarget.dataset.password_desc ? e.currentTarget.dataset.password : ''; 

        if (title && key) {
            wx.navigateTo({
                url: '../detail/detail?title=' + title + '&key=' + key + '&password=' + password 
                    + '&password_desc=' + password_desc + '&cover=' + cover,
                success: function () {
                    // nothing to do
                },
                fail: function () {
                    console.error("打开链接失败");
                }
            })
        }
    },
    onPullDownRefresh: function() {
        console.log('下拉刷新')
        let that = this;
        // 重新请求全局配置文件
        app.fetchGlobalConfig(function (status, result) {
            if (status) {
                wx.setStorage({
                    key: "config",
                    data: result
                })
                that.checkoutAD();
            }
        });
        // 重新请求首页博文
        that.firstTimeLoadBlogPageData(function(status) {
            // 主动停止下拉操作
            wx.stopPullDownRefresh();
        });     
    }

})